package cuit.epoch.pymjl.security.controller;


import cuit.epoch.pymjl.security.common.result.CommonResult;
import cuit.epoch.pymjl.security.common.result.Result;
import cuit.epoch.pymjl.security.common.result.ResultUtils;
import cuit.epoch.pymjl.security.common.utils.UUIDUtil;
import cuit.epoch.pymjl.security.common.utils.UploadImage;
import cuit.epoch.pymjl.security.entity.User;
import cuit.epoch.pymjl.security.entity.dto.UserDTO;
import cuit.epoch.pymjl.security.mapper.UserMapper;
import cuit.epoch.pymjl.security.service.IUserService;
import cuit.epoch.pymjl.security.service.impl.RoleResourceServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.*;
import java.util.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Pymjl
 * @since 2022-08-20
 */
@Slf4j
@RestController
@RequestMapping("/user")
@Validated
public class UserController {
    @Autowired
    RoleResourceServiceImpl roleResourceService;

    @Autowired
    IUserService userService;

    @Autowired
    UserMapper userMapper;

    //注册
    @PostMapping("/register")
    public CommonResult<String> registry(@RequestParam("username") String username,
                                         @RequestParam("userid") String userid,
                                         @RequestParam("email") String email,
                                         @RequestParam("password") String password,
                                         @RequestParam("academy") String academy,
                                         @RequestParam("campus") String campus,
                                         @RequestParam("sex") String sex
//                                         @RequestParam("avatar") MultipartFile avatar
    ) throws IOException {
        UserDTO userDTO = new UserDTO();
//        userDTO.setAvatar(avatar.getBytes());
        userDTO.setUsername(username);
        userDTO.setCampus(campus);
        userDTO.setEmail(email);
        userDTO.setAcademy(academy);
        userDTO.setPassword(password);
        userDTO.setSex(sex);
        userDTO.setUserid(userid);
        userService.registry(userDTO);
        return ResultUtils.success();
    }

    //    //修改密码
//    @PutMapping("/updatepassword")
//    public CommonResult<String> updatepassword(@Valid @RequestBody User user) {
//        boolean b = userMapper.updateByEmail(user);
//        return b==true?ResultUtils.success():ResultUtils.fail();
//    }
    //更新用户信息
    @PutMapping("/updateuser")
    public Result updateuser(@Valid @RequestBody User user1) {
        return Result.suc(userService.updateuser(user1));
    }

    //获取用户头像
    @GetMapping("/image")
    public Result getImage(@RequestParam String id) {
        User user = (User) userMapper.selectByEmail(id);
        String newFileName = user.getAvatar();
        //先前端发送文件url
        Map<String, String> map = new HashMap<>();
        //返回路径加文件名
//        map.put("url", "http://192.168.10.100:8080/home/picture/" + newFileName);
        map.put("url", "http://111.229.186.198:8080/home/picture/" + newFileName);
        return Result.suc(map);
    }

    //更换用户头像
    @PostMapping("/updateuseravatar")
    public Result updateavatar(@RequestParam String username, @RequestParam MultipartFile file) throws IOException {

        //重命名上传文件
        String newFileName = UUIDUtil.generate() + ".jpg";
        //从数据库查询之前是否有头像，如果有则删除
        User user = (User) userMapper.selectByEmail(username);
        try {
            UploadImage.sshSftpDel(user.getAvatar());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        //文件名保存到数据库
        userService.updateUserAvatar(username, newFileName);
        try {
            //将图片以newFileName命名上传到服务器
            UploadImage.sshSftp(file.getBytes(), newFileName);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return Result.suc();
    }
   /*@PostMapping("/updateuseravatar")
    public Result updateavatar(@RequestPart("username") String username,
                               @RequestPart("image") MultipartFile avatar) throws IOException {
        return Result.suc(userService.updateavatar(username, avatar.getBytes()));
    }*/

    //登录
    @PostMapping("/login")
    public Result login(@RequestBody User user) {
        return Result.suc02(userService.selectByEmail(user.getUsername()), userService.login(user.getUsername(), user.getPassword()));
    }

    //查询数据库中的user表中的email字段是否存在
    @GetMapping("/selectemail")
    public Integer selectEmail(@RequestParam String email) {
        Object list = userMapper.selectByEmail(email);
        String pId = String.valueOf(list);
        String nu = "null";
        log.info(pId);
        System.out.println(pId);
        return pId.equals(nu) ? 1 : 0;
    }

    //测试接口（需要进行权限验证）
    @GetMapping("/test")
    @PreAuthorize("hasAuthority('admin:test')")
    public CommonResult<String> test() {
        return ResultUtils.success("test");
    }

    //根据id获取头像base64
    @GetMapping("/image64")
    public Result getImage64(@RequestParam String id) {
        User user = (User) userMapper.selectByEmail(id);
        String base64= null;
        try {
            base64 = UploadImage.sshSftpDownload(user.getAvatar());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        //先前端发送文件url
        Map<String, String> map = new HashMap<>();
        //返回路径加文件名
        map.put("url",base64);
        return Result.suc(map);
    }

}

